package dbinit;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import core.category.model.CategoryType;
import core.util.HibernateCoreUtil;

public class InitCategoryType 
{
	@SuppressWarnings("unchecked")
	public static Long createOrGetUuidByName(String type)
	{
		CategoryType ct = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		Long uuid = 0L;
		try
		{
			transaction = session.beginTransaction();
			 List <CategoryType> cts = session.createQuery("from CategoryType ct where ct.type='"+type+"'").list();
			 if(cts.size() == 0)
			 {
				uuid = doinit(type);
			 }
			 else
			 {
				 Iterator <CategoryType> ctItr = cts.iterator(); 
				 while(ctItr.hasNext())
				 {
					 ct = ctItr.next() ;
					 break ;
				 }
				 uuid = ct.getUuid();
			 }
			 transaction.commit();
		}
		catch(HibernateException e)
		{
			e.printStackTrace();
		}
		return uuid;
	}
	
	public static CategoryType getCategoryTypeByUuid(Long uuid)
	{
		CategoryType ct = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				ct = (CategoryType) session.get(CategoryType.class, uuid);
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return ct ;
	}
	public static Long doinit(String type)
	{
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		CategoryType ct = new CategoryType();
		ct.setType(type);
		Long uuid = null;
		try
		{
			transaction = session.beginTransaction();
		    uuid = (Long)session.save(ct);
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		return uuid ;
	}

}
